import { Component, OnInit,Input,ViewChild,ElementRef } from '@angular/core';
import {Router,NavigationExtras} from '@angular/router';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import * as moment from 'moment' 
import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';
import { NzMessageService } from 'ng-zorro-antd/message';



@Component({
  selector: 'app-addclue',
  templateUrl: './addclue.component.html',
  styleUrls: ['./addclue.component.scss']
})
export class AddclueComponent implements OnInit {
  @ViewChild('clickEvent') myclick:any;
  @ViewChild('select') select:any;
  @Input() name:any;
    // private select:ElementRef
    public isExpand:boolean = false;
    //区域数据
    public areaData: any;
    //省级联动
    public provinces:any[];
    //市级联动
    public cities:any[];
    //县级联动
    public counties:any[];
    addressDetails: any[]=[];
    public session:any = window.sessionStorage;
    public sessionDepart:any = JSON.parse(window.sessionStorage.getItem('organizations'))[0];
    public  nodes = [];
    public expandKey:any;

  constructor(public nzMessage:NzMessageService, private el:ElementRef,public orgService:OrgService,public clue:ClueService,public router:Router,public clueData:ClueDataService) {
    this.areaData = clueData.area;
   }
  public flag:boolean=false;
  public flags:boolean=false;
  public sortValue:any="1001";
  public getSelectValue:any="0";
  public expandKeys:any;
  public listOfOption = [];
  public userName = window.sessionStorage.getItem('realName');
  public selectValue:any=[{
    name:"法人",value:"0"
  },{
    name:"个人",value:"1"
  }];

  //线索来源json

  public clueList:any={
    "partyName":"",//当事人名称
    "address" :{
      "province":null,"city":null,"county":null,"detailed":null
    },//地址
    phone:"",//联系电话
    otherPhone:"",//其他联系方式
    clueSource:this.sortValue,//线索来源
    clueStatus:"02",	//线索状态
    registerContent:"",	//案源登记内容
    registerPerson:this.userName,//登记人
    registerDepart:"",	// 登记机关
    registerNumber:"",	// 登记号
    registerDate:"",//登记时间
    caseProvider:{},//案件提供人
    remarks:"",
    addressDetails:"",
    partyPerson:"",
    partyPersonId:this.session.getItem('userId'),
    partyDepart:"",
    registerDepartName:"",
    createUser:this.session.getItem('userId')
    };
  public caseProviderstring="";
  public addressstring="";

  public myDoc:any;
  public myflag:boolean;
  public v1:any;
  public v2:any;

  public date:Date = new Date();

 
  ngOnInit() {  
    this.clueList.partyDepart = this.sessionDepart.orgId;
    this.clueList.registerDate = moment(this.date).format('YYYY-MM-DD HH:mm:ss')
    this.provinces = this.areaData;
    if(!this.session.getItem('areaData')) {
      let id = this.session.getItem('accessToken') || "";
      this.orgService.getAreaById(id).subscribe((data) => {
        if (data['rel'] == true) {
          this.session.setItem('areaData', JSON.stringify(data['data']));
          let nodesData = data['data'];
          this.nodes = this.DataProcess(nodesData, '0', '机构');


           // 登记机关赋值
          for (let index = 0; index < this.sessionDepart.length; index++) {
            if(this.sessionDepart[index].orgTypeName=="机构"){
              this.clueList.registerDepart = this.sessionDepart[index].orgId;
            this.v2 = this.sessionDepart[index].orgId;
            this.v1 = this.sessionDepart[index].areaParentId;
            this.expandKeys=[this.v1.toString(),this.v2.toString()];
            
            } 
          }
        } else {
          alert(data['message']);
        }
      }, (error) => {
      });
    } else {
      let nodesData = JSON.parse(this.session.getItem('areaData'));      
      this.nodes = this.DataProcess(nodesData, '0', '机构');
      for (let j = 0; j < this.nodes.length; j++) {
        this.nodes[j]['children'] = this.DataProcess( nodesData, this.nodes[j]['value'],"机构");
      }
      // 登记机关赋值
      this.clueList.registerDepart =  this.sessionDepart.orgId;
      this.v2 = this.sessionDepart.orgId;
      this.v1 = this.sessionDepart.orgParentId;
      this.expandKeys=[this.v1.toString(),this.v2.toString()];
      this.clueList.registerDepartName = this.sessionDepart.orgName
    }
  }
  // 将后台返回的数据处理成符合树形结构 
  DataProcess(data, parentId, type) {
    let arrayList = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['orgTypeName'] == type && data[i]['orgParentId'] == parentId) {
        let obj = {
          'title': '', 
          'text': '',
          'value': '', 
          'key': '', 
          'parentId': '', 
          'children': []
        };
        obj.title = data[i]['orgName'] || "";
        obj.text = data[i]['orgName'] || "";
        obj.value = data[i]['orgId'] || "";
        obj.key = data[i]['orgId'] || "";
        obj.parentId = data[i]['orgParentId'] || "";
        obj.children = this.DataProcess(data, obj.value, '机构');
        if (obj.children.length <= 0) {
          obj['isLeaf'] = true;
        }
        arrayList.push(obj);
      }
    }
    return arrayList;
  }
    // 获取树中选中的节点
    getSelectedNodeList(key): void {
      let nodesData = JSON.parse(this.session.getItem('areaData'));
      this.listOfOption = this.DataProcess(nodesData, key, '部门');
      
      this.clueList.registerDepartName = this.select.getSelectedNodeList()[0].origin.title
    }

  //省级选择
  onProvinceChange(event){
   if(event!==null){
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.cities = this.provinces[0].children;
      this.addressDetails[0] = this.provinces[0].label;
      this.addressDetails[1] = this.addressDetails[2] = "";
    }else{
      this.clueList.address.province = null;
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[0] =this.addressDetails[1] = this.addressDetails[2] = "";
      this.cities = [];
      this.counties = [];
    }
  }
  //市级选择
  onCityChange(event){
    if(event!==null){
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      let currCity= this.cities.filter(city=>city.key==event);
      this.counties = currCity[0].children;
      this.addressDetails[1] = currCity[0].label;
      this.addressDetails[2] = "";
    }else{
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[1] = this.addressDetails[2] = "";
      this.counties = [];
    }
  }
  //县级选择
  onCountyChange(event){
    if(event!==null){
      let currCounty = this.counties.filter(county=>county.key==event);
      this.addressDetails[2] = currCounty[0].label;
      this.clueList.address.detailed = null;
    }else{
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[2]='';
    }
  }
  radiochang(e){
    this.getSelectValue = "0";
    if(e == "1001"){
      this.clueList.caseProvider={
        "jcr1":"", "ssdw1":"","jcr2":"","ssdw2":""
      }
    }else if(e == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
      this.clueList.caseProvider={
        "depname":"","atten":"","telnum":"","address":""
      }
    }else if(e == "1002"){
      this.clueList.caseProvider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
     this.onChange(event);
    }
  }
  onChange(event){
    if(event=="0"){
      this.clueList.caseProvider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
    }else if(event=="1"){
      this.clueList.caseProvider={
        "type":"1","name":"","idnum":"","telnum":"","address":"","otherinfo":""
        }
    }
  }
  mysubmit(callback){   
  
    if(this.clueList.registerDate){
      let datetime = moment(this.clueList.registerDate).format('YYYY-MM-DD HH:mm:ss')
      this.clueList.registerDate = datetime
    }else{
      this.clueList.registerDate = ''
    }
    let  area= this.addressDetails.concat(this.clueList.address.detailed).join('')
    this.clueList.addressDetails = area;
    this.clueList.caseProvider=JSON.stringify(this.clueList.caseProvider);
    this.clueList.address= JSON.stringify(this.clueList.address);
   
    this.clueList.clueSource = this.sortValue;

    this.clueList.partyPerson = this.userName;

    // this.clueList.partyDepart = this.clueList.registerDepart;

    var list:any = JSON.stringify(this.clueList);

    this.clue.insertClue(list).subscribe(({data,code})=>{
      if(code==200){
        this.flag=true
        this.flags=false;
        
        if(callback){
          callback()
        }else{
          this.router.navigate(['/main/home/clue/previewdocument/',data.id]);
        }
      }else{
        this.flags=true;
      }
      
    })
  }

  dodoc(e){
    if(e){
      this.myDoc=e;
      this.myflag = true;
    }else{
      this.myflag = false;
    }
  }
  emitFather(){
    console.log('要弹框！！！！！！！');
  }
  fun(ev){
    this.myflag = ev;
  }


  // 关闭卡片
  closeCard(){
    this.isExpand  = false;
  }
  // 切换底部card
  cardToggle($event){
    if($event){
      this.isExpand  = $event
    }
  }
}
